//
//  MsgViewCtrl.m
//  WeiMo
//
//  Created by he weixian on 13-3-21.
//  Copyright (c) 2013年 . All rights reserved.
//

#import "MsgViewCtrl.h"

#import "KeyValueObject.h"
#import "JSONKit.h"
#import "RequestViewController.h"
#import "SVPullToRefresh.h"
#import "DLog.h"
#import "InterfaceDefine.h"
#import "FMManager.h"
#import "BDKNotifyHUD.h"
#import "SecondViewController.h"

#define kPageSize (@"20")

@interface MsgViewCtrl ()
{
    int mCurPage;
    bool mIsLastPage;
    bool mIsUpdate;
    MBProgressHUD *mHUD;
    
}

@property (nonatomic,retain) NSMutableArray *msgArray;//消息
@property(nonatomic,retain) NSTimer *timerLoadData;
@property (strong, nonatomic) BDKNotifyHUD *notify;

@property(nonatomic,retain) UITableView *msgTableView;
@property (nonatomic,retain) UIView *cityPopPickerView;
@property (nonatomic,retain) UIPickerView *cityPickerView;

@property (nonatomic,retain) NSArray *option_provinces; //省
@property (nonatomic,retain) NSArray *option_cities;     //市
@property (nonatomic,retain) NSMutableArray *option_showCitys;     //显示的市区

@property (nonatomic,copy) NSString *choosedProvinceId;       //记录选中的省
@property (nonatomic,copy) NSString *choosedCityId;           //记录选中的市
@end

@implementation MsgViewCtrl
@synthesize msgArray;
@synthesize timerLoadData;
@synthesize cityPopPickerView,cityPickerView;
@synthesize option_provinces,option_cities,option_showCitys;
@synthesize choosedProvinceId,choosedCityId;
@synthesize msgTableView;

- (void)dealloc
{
    self.msgArray = nil;
    [self.timerLoadData invalidate];
    self.timerLoadData = nil;
    self.cityPopPickerView = nil;
    self.option_provinces = nil;
    self.option_cities = nil;
    self.option_showCitys = nil;
    self.choosedProvinceId = nil;
    self.choosedCityId = nil;
    self.cityPickerView = nil;
    self.msgTableView = nil;
    [super dealloc];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self)
    {
        self.title = @"通告";
        self.tabBarItem.image = [UIImage imageNamed:@"msg"];
    }
    return self;
}

-(void)viewDidUnload
{
    [super viewDidUnload];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [[UIBarButtonItem appearance] setTintColor:[UIColor blackColor]];
    
    self.msgArray = nil;
    mIsUpdate = false;
    
    self.choosedProvinceId = @"";
    self.choosedCityId = @"";
    
    CGRect rect = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height-44-49);
    self.msgTableView = [[[UITableView alloc] initWithFrame:rect] autorelease];
    self.msgTableView.backgroundColor =[UIColor colorWithRed:236.0/255 green:237.0/255 blue:241.0/255 alpha:1];
    self.msgTableView.dataSource = self;
    self.msgTableView.delegate = self;
    [self.view addSubview:self.msgTableView];
    //上拉事件
    [self.msgTableView addPullToRefreshWithActionHandler:^{
        mCurPage=1;
        mIsUpdate = true;
        //mCurPage = mCurPage + 5;
        self.msgArray = nil;
        self.timerLoadData = [NSTimer scheduledTimerWithTimeInterval:0.8 target:self selector:@selector(getMessageDatas) userInfo:nil repeats:NO];
        
    }];
    
    //下拉事件
    [self.msgTableView addInfiniteScrollingWithActionHandler:^{
        DLog("load data = %d",mCurPage);
        if(!mIsLastPage)
        {
             DLog("load2 data = %d",mCurPage);
            mCurPage++;
            //[self getMessageDatas];
            self.timerLoadData = [NSTimer scheduledTimerWithTimeInterval:0.8 target:self selector:@selector(getMessageDatas) userInfo:nil repeats:NO];
        }
        else
        {
            [self.msgTableView.infiniteScrollingView stopAnimating];
        }
        
    }];
    
    UIImage *faceImage = [UIImage imageNamed:@"sendMsg.png"];
    UIButton *face = [UIButton buttonWithType:UIButtonTypeCustom];
    face.bounds = CGRectMake( 0, 0, faceImage.size.width, faceImage.size.height );
    [face setImage:faceImage forState:UIControlStateNormal];
    [face addTarget:self action:@selector(sendMessageToSender) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *leftButtonItem = [[UIBarButtonItem alloc] initWithCustomView:face];
    self.navigationItem.leftBarButtonItem = leftButtonItem;
    [leftButtonItem release];
    
    UIImage *faceImage2 = [UIImage imageNamed:@"secondMenu.png"];
    UIButton *optionsChoose = [UIButton buttonWithType:UIButtonTypeCustom];
    optionsChoose.bounds = CGRectMake( 0, 0, faceImage2.size.width, faceImage2.size.height );
    [optionsChoose setImage:faceImage2 forState:UIControlStateNormal];
    [optionsChoose addTarget:self action:@selector(optionsChooseClickedEvent) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *rightButtonItem = [[UIBarButtonItem alloc] initWithCustomView:optionsChoose];
    self.navigationItem.rightBarButtonItem = rightButtonItem;
    [rightButtonItem release];
}

- (void)viewWillAppear:(BOOL)animated
{
    if(self.msgArray==nil)
    {
        mCurPage = 1;
        mHUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
        [self.navigationController.view addSubview:mHUD];
        mHUD.delegate = self;
        [self getMessageDatas];
        [mHUD show:YES];
    }
    
    [self showMsgTabBar];
}

- (void)didReceiveMemoryWarning
{
    DEnter();
    [super didReceiveMemoryWarning];
}

#pragma mark - private methods

//显示TabBar
- (void)showMsgTabBar
{
    if (self.tabBarController.tabBar.hidden == NO)
    {
        return;
    }
    UIView *contentView;
    if ([[self.tabBarController.view.subviews objectAtIndex:0] isKindOfClass:[UITabBar class]])
        
        contentView = [self.tabBarController.view.subviews objectAtIndex:1];
    
    else
        
        contentView = [self.tabBarController.view.subviews objectAtIndex:0];
    contentView.frame = CGRectMake(contentView.bounds.origin.x, contentView.bounds.origin.y,  contentView.bounds.size.width, contentView.bounds.size.height - self.tabBarController.tabBar.frame.size.height);
    self.tabBarController.tabBar.hidden = NO;
    
}

- (CGFloat)returnLableHeightWithString:(NSString *)string
{
    UIFont *font = [UIFont systemFontOfSize:15.0];
    CGSize size = [string sizeWithFont:font constrainedToSize:CGSizeMake(256, 1000) lineBreakMode:NSLineBreakByTruncatingTail];
    return size.height;
}


- (void)displayNotification:(NSString *)text {
    if (self.notify.isAnimating) return;
    float y = self.msgTableView.contentOffset.y + self.view.center.y;
    _notify.center = CGPointMake(self.view.center.x, y);
    self.notify.text = text;
    [self.view addSubview:self.notify];
    [self.notify presentWithDuration:1.0f speed:0.6f inView:self.view completion:^{
        [self.notify removeFromSuperview];
    }];
}

- (BDKNotifyHUD *)notify {
    if (_notify != nil) return _notify;
    _notify = [BDKNotifyHUD notifyHUDWithImage:nil text:@"发送成功"];
    return _notify;
}

-(void)getMessageDatas
{
    NSString *urlStr = [NSString stringWithFormat:@"%@/%@",kHttpHost,kGetAllJobInfo];
    
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:urlStr]];
    NSMutableDictionary *dic = [[[NSMutableDictionary alloc] init] autorelease];
    
    [dic setObject:[NSString stringWithFormat:@"%d",mCurPage] forKey:@"startPage"];
    [dic setObject:kPageSize forKey:@"pageSize"];
    
    [dic setObject:self.choosedCityId forKey:@"cityid"];
    [dic setObject:self.choosedProvinceId forKey:@"provinceid"];
    
    NSString *postStr = [dic JSONString];
    [request appendPostData:[postStr dataUsingEncoding:NSUTF8StringEncoding]];
    [request setRequestMethod:@"POST"];
    request.delegate = self;
    [request startAsynchronous];
}


-(void)requestJobWithJobId:(NSNumber *)jobId andModelsId:(NSNumber *)userId
{
    NSMutableDictionary *dic = [[[NSMutableDictionary alloc] init] autorelease];
    NSString *userType = [[FMManager sharedInstance] modeIdentify];
    [dic setObject:jobId forKey:@"jobsId"];
    [dic setObject:userId forKey:@"userId"];
    [dic setObject:userType forKey:@"userType"];
    NSString *postStr = [dic JSONString];
    
    NSString *urlStr = [NSString stringWithFormat:@"%@/%@",kHttpHost,kRequestJob];
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:urlStr]];
    [request appendPostData:[postStr dataUsingEncoding:NSUTF8StringEncoding]];
    [request setRequestMethod:@"POST"];
    request.delegate = self;
    [request startAsynchronous];
}

//城市筛选
- (void)optionsChooseClickedEvent
{
    if (self.cityPopPickerView == nil)
    {
        [self getCityDatasFromLocalJson];
        
        float oY = self.view.frame.size.height - 216 - 44;
        CGRect rect = CGRectMake(0, oY, self.view.frame.size.width, 216+44);
        self.cityPopPickerView = [[[UIView alloc] initWithFrame:rect] autorelease];
        self.cityPopPickerView.backgroundColor = [UIColor clearColor];
        
        UIToolbar *toolBar = [[[UIToolbar alloc] init] autorelease];
        toolBar.barStyle = UIBarStyleBlackTranslucent;
        toolBar.autoresizingMask = UIViewAutoresizingFlexibleHeight;
        [toolBar sizeToFit];
        CGRect frame = toolBar.frame;
        frame.size.height = 44.0f;
        toolBar.frame = frame;
        
        UIBarButtonItem *doneBtn =[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(clickedDoneButtonEvent)];
        UIBarButtonItem *flexibleSpaceLeft = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
        
        NSArray *toolArray = [NSArray arrayWithObjects:flexibleSpaceLeft, doneBtn, nil];
        [toolBar setItems:toolArray];
        [doneBtn release];
        
        [self.cityPopPickerView addSubview:toolBar];
        
        rect.origin.y = 44;
        rect.size.height = 216;
        self.cityPickerView = [[[UIPickerView alloc] initWithFrame:rect] autorelease];
        self.cityPickerView.dataSource = self;
        self.cityPickerView.delegate = self;
        self.cityPickerView.showsSelectionIndicator = YES;
        [self.cityPickerView sizeToFit];
        [self.cityPopPickerView addSubview:self.cityPickerView];
    }
    
    [self.view addSubview:self.cityPopPickerView];
}

//发送通告
-(void)sendMessageToSender
{
    FMManager *fm = [FMManager sharedInstance];
    if(fm.userId)
    {
        RequestViewController *requestCtrl = [[[RequestViewController alloc] initWithStyle:UITableViewStyleGrouped] autorelease];
        requestCtrl.delegate = self;
        [self.navigationController pushViewController:requestCtrl animated:YES];
    }
    else
    {
        [FMManager showAlertViewTitle:@"亲" message:@"请登录后并填写个人资料后，才可以发布消息"];
    }
}

//获取数据
- (void)getCityDatasFromLocalJson
{
    NSString *filePath1 = [[NSBundle mainBundle] pathForResource:@"province" ofType:@"json"];
    NSString *jsonString1 = [NSString stringWithContentsOfFile:filePath1 encoding:NSUTF8StringEncoding error:nil];
    self.option_provinces = [jsonString1 objectFromJSONString];
    
    NSString *filePath2 = [[NSBundle mainBundle] pathForResource:@"city" ofType:@"json"];
    NSString *jsonString2 = [NSString stringWithContentsOfFile:filePath2 encoding:NSUTF8StringEncoding error:nil];
    self.option_cities = [jsonString2 objectFromJSONString];
    
    NSDictionary *dic = [self.option_provinces objectAtIndex:0];
    [self getOptionShowCitysFromCityDatas:[dic objectForKey:@"provinceid"]];
    self.choosedProvinceId = [dic objectForKey:@"provinceid"];
    self.choosedCityId = @"";
}

//获取所属地市数据
- (void)getOptionShowCitysFromCityDatas:(NSString *)parentid
{
    self.option_showCitys = [[[NSMutableArray alloc] init] autorelease];
    NSMutableDictionary *firstDic = [[NSMutableDictionary alloc] init];
    [firstDic setValue:@"全部" forKey:@"city"];
    [firstDic setValue:@"" forKey:@"cityid"];
    [self.option_showCitys addObject:firstDic];
    [firstDic release];
    
    for (int i=0; i<self.option_cities.count; i++)
    {
        NSDictionary *otherDic = [self.option_cities objectAtIndex:i];
        NSString *provinceId = [otherDic objectForKey:@"father"];
        if ([provinceId isEqualToString:parentid])
        {
            [self.option_showCitys addObject:otherDic];
        }
    }
}

- (void)clickedDoneButtonEvent
{
    [self.cityPopPickerView removeFromSuperview];
    
    mCurPage = 1;
    DLog(@"province:%@,city:%@",self.choosedProvinceId,self.choosedCityId);
    self.msgArray = nil;
    [self.msgTableView reloadData];
    [self getMessageDatas];
}

#pragma mark - table view

#pragma mark UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(self.msgArray)
    {
        return self.msgArray.count;
    }
    else
    {
        return 0;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *msgCellDefine = @"msgCellDefine";
    MsgCell *cell = [tableView dequeueReusableCellWithIdentifier:msgCellDefine];
    if (cell == nil)
    {
        cell = [[[MsgCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:msgCellDefine] autorelease];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.delegate = self;
    }
    
    NSDictionary *item = [self.msgArray objectAtIndex:indexPath.row];
    
    cell.title.text = [item objectForKey:@"modelsName"]; //发布者
    cell.content.text = [item objectForKey:@"jobsInformation"];  //内容
    cell.time.text = [item objectForKey:@"createTimeStr"];//时间
    cell.sender.tag = indexPath.row + 100;
    cell.inboxSenderId = [item objectForKey:@"userId"];
    cell.userType = [item objectForKey:@"userType"];
    NSString *numObj = [item objectForKey:@"userId"];
    NSString *url = [NSString stringWithFormat:@"%@/photo/%@/small_%@",kHttpHost,numObj,[item objectForKey:@"modelsAvatarstr"]];
    
    //DLog(@"url = %@",url);
    cell.headImageUrl = url;//头像
    [cell refreshRect];
    
    return cell;
}

#pragma mark UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //KeyValueObject *item = [self.msgArray objectAtIndex:indexPath.row];
    NSDictionary *item = [self.msgArray objectAtIndex:indexPath.row];
    float h1 = 18;
    //float h1 = [self returnLableHeightWithString:[item objectForKey:@"modelsName"]];
    float h2 = [self returnLableHeightWithString:[item objectForKey:@"jobsInformation"]];
    float h3 = 70;
    float height = h1 + h2 + h3;
    return height;
}

#pragma mark - picker view

#pragma mark UIPickerViewDataSource

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 2;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    if (component == 0)
    {
        return self.option_provinces.count;
    }
    else
    {
        return self.option_showCitys.count;
    }
}

#pragma mark UIPickerViewDelegate

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
    if (component == 0)
    {
        UILabel *proLable = [[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 140, 44)] autorelease];
        proLable.backgroundColor = [UIColor clearColor];
        proLable.text = [[self.option_provinces objectAtIndex:row] objectForKey:@"province"];
        proLable.font = [UIFont systemFontOfSize:18.0];
        
        return proLable;
    }
    else
    {
        UILabel *cityLable = [[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 140, 44)] autorelease];
        cityLable.backgroundColor = [UIColor clearColor];
        cityLable.text = [[self.option_showCitys objectAtIndex:row] objectForKey:@"city"];
        cityLable.font = [UIFont systemFontOfSize:18.0];
        
        return cityLable;
    }
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    if (component == 0)
    {
        self.choosedProvinceId = [[self.option_provinces objectAtIndex:row] objectForKey:@"provinceid"];
        
        [self getOptionShowCitysFromCityDatas:self.choosedProvinceId];
        
        [self.cityPickerView reloadComponent:1];
        [self.cityPickerView selectRow:0 inComponent:1 animated:YES];
        self.choosedCityId = @"";
    }
    else
    {
        NSDictionary *selectedDic = [self.option_showCitys objectAtIndex:row];
        self.choosedCityId = [selectedDic objectForKey:@"cityid"];
    }
}

#pragma mark - ASIHTTPRequestDelegate

- (void)requestFinished:(ASIHTTPRequest *)request
{
    if(mHUD)
    {
        mHUD.hidden = YES;
    }
    
    if(mIsUpdate)
    {
        [self.msgTableView.pullToRefreshView stopAnimating];
    }
    
    NSString *urlStr = [NSString stringWithFormat:@"%@",request.url];
    NSString *action = @"";
    if (urlStr.length > 0)
    {
        NSArray *array = [urlStr componentsSeparatedByString:@"/"];
        action = [array objectAtIndex:(array.count - 1)];
    }
    DLog(@"%@",action);
    
    NSData *data = [request responseData];
    NSArray *array = [data objectFromJSONData];
    
    if([action isEqualToString:(kGetAllJobInfo)])
    {
        if(array == nil || array.count == 0)
        {
           
            return;
        }
        
        NSString *item0 = [array objectAtIndex:0];
        if(![item0 isEqualToString:kResponseOk])
        {
            return;
        }
        
        NSDictionary *datadic = [array objectAtIndex:1];
        
        NSMutableArray *tempArray = [datadic objectForKey:@"data"];
        if(tempArray.count == 0)
        {
            mIsLastPage = true;
            [self.msgTableView.infiniteScrollingView stopAnimating];
            return;
        }
        
        NSString *modelsAvatarstr = @"modelsAvatarstr";
        NSString *createTimeStr = @"createTimeStr";
        NSString *jobsTyp = @"jobsTyp";
        NSString *jobsId = @"jobsId";
        NSString *modelsName = @"modelsName";
        NSString *userId = @"userId";
        NSString *jobsInformation = @"jobsInformation";
        NSString *userType = @"userType";
        
        if (mCurPage == 1)
        {
            self.msgArray = [[[NSMutableArray alloc] init] autorelease];
        }
        else
        {
            if(self.msgArray == nil)
            {
                self.msgArray = [[[NSMutableArray alloc] init] autorelease];
            }
        }
        
        for(int i = 0; i< tempArray.count; i++)
        {
            NSDictionary *item = [tempArray objectAtIndex:i];
            NSMutableDictionary *dic = [[[NSMutableDictionary alloc] init] autorelease];
            [dic setObject:[item objectForKey:modelsAvatarstr] forKey:modelsAvatarstr];
            [dic setObject:[item objectForKey:createTimeStr] forKey:createTimeStr];
            [dic setObject:[item objectForKey:jobsTyp] forKey:jobsTyp];
            [dic setObject:[item objectForKey:jobsId] forKey:jobsId];
            [dic setObject:[item objectForKey:modelsName] forKey:modelsName];
            NSNumber *u1 = [item objectForKey:userId];
            NSString *strU1 = [NSString stringWithFormat:@"%@",u1];
            [dic setObject:strU1 forKey:userId];
            [dic setObject:[item objectForKey:jobsInformation] forKey:jobsInformation];
            NSNumber *u2 = [item objectForKey:userType];
            NSString *strU2 = [NSString stringWithFormat:@"%@",u2];
            [dic setObject:strU2 forKey:userType];
            [self.msgArray addObject:dic];
        }
        
        [self.msgTableView reloadData];
    }
    else if([action isEqualToString:(kRequestJob)])
    {
        if(array == nil || array.count == 0)
        {
            return;
        }
        
        NSString *item0 = [array objectAtIndex:0];
        if([item0 isEqualToString:kResponseOk])
        {
            [self displayNotification:@"发送成功"];
            return;
        }
        else if([item0 isEqualToString:kResponseOk2])
        {
            [self displayNotification:@"已经发送过了"];
        }
        else
        {
            [self displayNotification:@"发送失败"];
        }
    }
}

- (void)requestFailed:(ASIHTTPRequest *)request
{
    NSError *error = [request error];
    if (error)
    {
        if(mIsUpdate)
        {
            [self.msgTableView.pullToRefreshView stopAnimating];
        }
        //NSLog(@"error = %@",error);
    }
    
    if(mHUD == nil)
    {
        mHUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
        [self.navigationController.view addSubview:mHUD];
        mHUD.delegate = self;
        [mHUD show:YES];
    }
    mHUD.mode =MBProgressHUDModeText;
    mHUD.labelText = @"网络链接失败";
    [mHUD hide:YES afterDelay:1.5];
}

#pragma mark - MsgCellDelegate
- (void)senderMessageClicked:(int) tag
{
    FMManager *fm = [FMManager sharedInstance];
    if(fm.userId)
    {
        NSDictionary *item = [self.msgArray objectAtIndex:tag - 100];
        NSNumber *jobsId = [item objectForKey:@"jobsId"];
        NSNumber *userId = [[[NSNumber alloc] initWithInt:fm.userId.intValue] autorelease];
        [self requestJobWithJobId:jobsId andModelsId:userId];
    }
    else
    {
        [FMManager showAlertViewTitle:@"亲" message:@"请登录后并填写个人资料后，才可以发送个人资料"];
    }
   
}

- (void)clickedInboxSender:(NSString *)senderId userType:(NSString *)userType
{
    if(userType && ![userType isEqualToString:@"0"])
    {
        SecondViewController *modelCtrl = [[[SecondViewController alloc] init] autorelease];
        modelCtrl.editType=@"isMsg";
        modelCtrl.userId = senderId;
        modelCtrl.userIdentify = userType;
        [self.navigationController pushViewController:modelCtrl animated:YES];
        [modelCtrl myRefeash];
    }
}

#pragma mark - RequestViewControllerDelegate
-(void)comiOK
{
    self.msgArray = nil;
    mCurPage = 1;
}

#pragma mark -
#pragma mark MBProgressHUDDelegate methods

- (void)hudWasHidden:(MBProgressHUD *)hud {
	// Remove HUD from screen when the HUD was hidded
	[mHUD removeFromSuperview];
	[mHUD release];
	mHUD = nil;
}

@end